import Module from "./module"

export default class ModuleCollection {
  
  root

  constructor (rawRootModule) {
    this.register([], rawRootModule)
  }

  register (path, rawModule) {
    const newModule = new Module(rawModule)
    if  (path.length === 0) {
      this.root = newModule
    } else {
      const parent = this.get(path.slice(0, -1))
      parent.addChild(path[path.length - 1], newModule)
    }
    if (rawModule.modules) {
      for (const [key, rawChildModule] of Object.entries(rawModule.modules)) {
        this.register([...path, key], rawChildModule)
      }
    }
  }

  get (path) {
    return path.reduce((module, key) => module.getChild(key), this.root)
  }

  getNamespace (path) {
    let module = this.root
    return path.reduce((namespace, key) => {
      module = module.getChild(key)
      return namespace + (module.namespaced ? key + '/' : '')
    }, '')
  }

}